package service;

import com.distribute.pojo.PageInfo;
import com.distribute.pojo.Result;
import com.distribute.pojo.enums.ServiceType;
import com.distribute.pojo.user.Tenant;
import com.distribute.pojo.user.User;
import com.distribute.utils.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import constant.DSConstants;
import constant.MediaTypeConstants;
import core.api.ApiClient;
import exception.ApiException;
import service.api.TenantService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DSTenantService implements TenantService {

    private final ApiClient apiClient;

    public DSTenantService(ApiClient apiClient) {
        this.apiClient = apiClient;
    }

    @Override
    public ServiceType getServiceType() {
        return ServiceType.TENANT;
    }

    @Override
    public boolean verifyTenantCode(String tenantCode) {
        if (tenantCode == null || tenantCode.isEmpty()) {
            throw new ApiException("userName is null");
        }
        Map<String, String> body = new HashMap<>();
        body.put(DSConstants.TENANT_CODE, tenantCode);
        Result result = apiClient.get(DSConstants.USER_VERIFY_USER_NAME_PATH, Result.class, tenantCode.trim());
        if (result.isFailed()) {
            throw new ApiException(result.getMsg());
        }
        return result.isSuccess();
    }

    @Override
    public Tenant createTenant(String tenantCode, Integer queueId, String tenantDesc) {
        if (!verifyTenantCode(tenantCode)) {
            throw new ApiException("userName verify is failed");
        }
        Map<String, Object> body = new HashMap<>();
        body.put(DSConstants.TENANT_CODE, tenantCode);
        body.put(DSConstants.QUEUE_ID, queueId);
        body.put(DSConstants.DESCRIPTION, tenantDesc);

        Result result = apiClient.post(DSConstants.TENANT_CREATE_PATH, body, MediaTypeConstants.MEDIA_TYPE_FORM, Result.class);
        if (result.isFailed()) {
            throw new ApiException(result.getMsg());
        }
        return JsonUtils.toBean(result.getData(), Tenant.class);
    }

    @Override
    public Tenant getTenant(String tenantCode) {
        if (tenantCode == null || tenantCode.isEmpty()) {
            throw new ApiException("userName is null");
        }
        Result result = apiClient.get(DSConstants.TENANT_QUERY_PATH, Result.class, 10, 1, tenantCode);
        if (result.isFailed()) {
            throw new ApiException(result.getMsg());
        }
        PageInfo pageInfo = JsonUtils.toBean(result.getData(), PageInfo.class);

        String content = JsonUtils.converString(pageInfo.getTotalList());
        List<Tenant> tenants = JsonUtils.toList(content, new TypeReference<List<Tenant>>() {
        });

        if (tenants != null && !tenants.isEmpty()) {
            return tenants.get(0);
        } else {
            return null;
        }

    }
}
